package com.bw.module_main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.view.View
import android.webkit.JavascriptInterface
import androidx.appcompat.app.AlertDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.common.base.BaseActivity
import com.bw.common.dialog.AppUpdateDialog
import com.bw.common.path.RouthPath
import com.bw.module_main.databinding.ActivityMainBinding
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint

//@Route(path = "/new/activity")
@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var mAppUpdateDialog: AppUpdateDialog
    private var needUserPermissions = arrayListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.RECORD_AUDIO,
    )


    private var unGrantPermissions = arrayListOf<String>()


    private var hasUnGranted = false

    override fun getLayoutId(): Int = R.layout.activity_main

    override fun initViews() {
        appUpdateDialog()
        loadWebView()
    }

    /**
     * App更新
     */
    private fun appUpdateDialog() {
        var hasNewVersion = MMKV.defaultMMKV().decodeBool("has_new_version", true)
        mAppUpdateDialog = AppUpdateDialog(this@MainActivity)
        if (hasNewVersion) {
            MMKV.defaultMMKV().encode("has_new_version", false)
            mDataBind.wbTencent.postDelayed({
                mAppUpdateDialog.show()
            }, 2000)
        }

    }

    private fun loadWebView() {
        var homeUrl = MMKV.defaultMMKV().decodeString("home_url", "")
        mDataBind.wbTencent.loadUrl(homeUrl)
        mDataBind.wbTencent.view.overScrollMode = View.OVER_SCROLL_NEVER
        //添加JS交互
        mDataBind.wbTencent.addJavascriptInterface(
            WebViewJsInterface(),
            "androidinfo"
        ) //androidinfo是JS中调用时的名称，类似Window.androidinfo

        //延迟检查用户权限
        mDataBind.wbTencent.postDelayed({
            autoRequestPermission()
        }, 1000)
    }


    private fun autoRequestPermission(): Boolean {
        //判断是否是Android6.0，动态申请权限

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //清理历史未授权的权限
            unGrantPermissions.clear()
            //检查用户是否同意过权限
            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED) {
                    unGrantPermissions.add(it)
                }
            }
            //发起用户授权
            if (unGrantPermissions.size > 0) {
                requestPermissions(unGrantPermissions.toTypedArray(), 100)
                return false
            }

        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //检查是都还存在没有授权的权限
        if (requestCode == 100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            unGrantPermissions.forEach {
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED) {
                    hasUnGranted = true
                }

            }
        }
        //给出提示，让用户去设置中手动开启权限
        if (hasUnGranted) {
            var builder = AlertDialog.Builder(this)
            builder.setTitle("权限提示")
            builder.setMessage("没有授权，请到应用详情中设置")
            builder.setPositiveButton("去设置") { dialog, _ ->
                {
                    dialog.dismiss()
                    hasUnGranted = false
                    openAppDetailPage()
                }
            }
            builder.setNeutralButton("取消") { dialog, _ ->
                {
                    dialog.dismiss()
                    hasUnGranted = false
                }
                builder.create().show()

            }
        }
    }


    /**
     * 打开应用详情
     */
    private fun openAppDetailPage() {
        var intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this.startActivity(intent)
    }


    /**
     * 跳转具体的业务模块
     */
    private fun jumpModuleActivity(moduleType: String) {
        //1.检查用户权限是否全部同意
        var hasAllPermission = autoRequestPermission()
        if (!hasAllPermission) return
        //2.根据id跳git init 转到具体的业务模块
        when (moduleType) {
            "1", "2", "3", "4", "5", "6" -> ARouter.getInstance()
                .build(RouthPath.PATH_PROPERTY_PAGE).withString("moduleType", moduleType)
                .navigation()

            "7", "8", "9", "10" -> ARouter.getInstance().build(RouthPath.PATH_CULTURE_PAGE)
                .withString("moduleType", moduleType).navigation()

            "11", "12" -> ARouter.getInstance().build(RouthPath.PATH_ATTENDANCE_PAGE)
                .withString("moduleType", moduleType).navigation()

            "13", "14", "15" -> ARouter.getInstance().build(RouthPath.PATH_AUDIT_PAGE)
                .withString("moduleType", moduleType).navigation()

            else -> showToastMsg("敬请期待！！")
        }
    }



    inner class WebViewJsInterface {

        @JavascriptInterface
        fun androidparking(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidapply(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidvisit(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpatrol(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnews(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnoticelist(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidsign(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidattendance(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidproperty(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidcheckculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpeople(id: String) = jumpModuleActivity(id)
    }


}